import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import Link from 'umi/link';
import { formatMessage, FormattedMessage } from 'umi/locale';
import {
  Card,
  Button,
  Input,
  Table,
  Form,
  Modal,
  Divider,
  Icon,
  Tooltip,
  Radio,
  Select,
  Popconfirm,
  Row,
  Col,
  TreeSelect,
} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import styles from './style.less';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const { Option } = Select;
const { Search, TextArea } = Input;
const { TreeNode } = TreeSelect;

const ProductForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    classes,
    models,
    options,
    isShowJoinGateway,
    typeChange,
    handleModalVisible,
    handleAdd,
  } = props;

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      handleAdd(fieldsValue, form);
    });
  };

  const typeChangeHandle = e => {
    form.setFieldsValue({ isJoinGateway: 0 });
    typeChange(e);
  };

  // 组件树形控件 子节点渲染
  const renderTreeNodes = data =>
    data.map(item => {
      if (item.children) {
        return (
          <TreeNode title={item.name} key={item.id} value={item.id}>
            {renderTreeNodes(item.children)}
          </TreeNode>
        );
      }
      return <TreeNode title={item.name} key={item.id} value={item.id}></TreeNode>;
    });

  const renderOption = data => data.map(item => <Option key={item.id}>{item.name}</Option>);

  const onChange = value => {
    form.setFieldsValue({ model: undefined });
    const { dispatch } = props;
    dispatch({
      type: 'product/fetchModel',
      payload: { classId: value },
    });
  };

  return (
    <Modal
      title={formatMessage({ id: 'app.dm.product.add' })}
      destroyOnClose
      visible={modalVisible}
      width={618}
      onOk={okHandle}
      onCancel={() => handleModalVisible()}
    >
      <Divider orientation="left" style={{ color: '#999', margin: 0 }} dashed>
        <FormattedMessage id="app.dm.product.info" />
      </Divider>
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem label={formatMessage({ id: 'app.dm.product.info.name' })} colon={false}>
          {form.getFieldDecorator('name', {
            rules: [
              { required: true, message: formatMessage({ id: 'app.dm.product.info.name.place' }) },
            ],
          })(<Input placeholder={formatMessage({ id: 'app.dm.product.info.name.place' })} />)}
        </FormItem>
        <FormItem
          label={
            <span>
              <FormattedMessage id="app.dm.product.info.class" />
              <em className={styles.optional}>
                <Tooltip title={<FormattedMessage id="app.dm.product.info.class.help" />}>
                  <Icon type="info-circle-o" style={{ marginLeft: 4 }} />
                </Tooltip>
              </em>
            </span>
          }
          colon={false}
        >
          {form.getFieldDecorator('class', {
            rules: [
              { required: true, message: formatMessage({ id: 'app.dm.product.info.class' }) },
            ],
          })(
            <TreeSelect
              showSearch
              style={{ width: 485 }}
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              placeholder={formatMessage({ id: 'app.dm.product.info.class.place' })}
              allowClear
              treeDefaultExpandAll
              onChange={onChange}
            >
              {renderTreeNodes(classes)}
            </TreeSelect>,

            // <Cascader
            //   style={{ width: 242 }}
            //   options={classes}
            //   fieldNames={{ label: 'name', value: 'id', children: 'children' }}
            //   placeholder={formatMessage({ id: 'app.dm.product.info.class.place' })}
            //   onChange={onChange}
            // />,
          )}
        </FormItem>
        <FormItem label={formatMessage({ id: 'app.dm.product.info.model' })} colon={false}>
          {form.getFieldDecorator('model', {
            rules: [
              { required: true, message: formatMessage({ id: 'app.dm.product.info.model' }) },
            ],
          })(
            <Select
              allowClear
              style={{ width: 485 }}
              placeholder={formatMessage({ id: 'app.dm.product.info.model.place' })}
            >
              {renderOption(models)}
            </Select>,
          )}
        </FormItem>
      </div>
      <Divider orientation="left" style={{ color: '#999', margin: 0, marginTop: 24 }} dashed>
        <FormattedMessage id="app.dm.product.info.type" />
      </Divider>
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem label={formatMessage({ id: 'app.dm.product.info.type' })} colon={false}>
          {form.getFieldDecorator('type', {
            rules: [
              { required: true, message: formatMessage({ id: 'app.dm.product.info.type.place' }) },
            ],
            initialValue: 1,
          })(
            <RadioGroup onChange={typeChangeHandle}>
              <Radio value={1}>
                <FormattedMessage id="app.dm.product.info.type.device" />
              </Radio>
              <Radio value={2}>
                <FormattedMessage id="app.dm.product.info.type.gateway" />
              </Radio>
            </RadioGroup>,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.info.isJoinGateway' })}
          colon={false}
          style={{ display: isShowJoinGateway }}
        >
          {form.getFieldDecorator('isJoinGateway', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.info.isJoinGateway.place' }),
              },
            ],
            initialValue: 0,
          })(
            <RadioGroup ref={props.radio}>
              <Radio value={1}>
                <FormattedMessage id="app.dm.product.info.isJoinGateway.yes" />
              </Radio>
              <Radio value={0}>
                <FormattedMessage id="app.dm.product.info.isJoinGateway.no" />
              </Radio>
            </RadioGroup>,
          )}
        </FormItem>
      </div>
      <Divider orientation="left" style={{ color: '#999', margin: 0, marginTop: 24 }} dashed>
        <FormattedMessage id="app.dm.product.info.netdata" />
      </Divider>
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.info.netdata.nettype' })}
          colon={false}
        >
          {form.getFieldDecorator('net', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.info.netdata.nettype.place' }),
              },
            ],
            initialValue: 1,
          })(
            <Select style={{ width: 485 }}>
              <Option value={1}>
                <FormattedMessage id="app.dm.product.info.netdata.nettype.wifi" />
              </Option>
              <Option value={2}>
                <FormattedMessage id="app.dm.product.info.netdata.nettype.cellular" />
              </Option>
              <Option value={3}>
                <FormattedMessage id="app.dm.product.info.netdata.nettype.ethernet" />
              </Option>
              <Option value={4}>
                <FormattedMessage id="app.dm.product.info.netdata.nettype.other" />
              </Option>
            </Select>,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.info.netdata.protocol' })}
          colon={false}
        >
          {form.getFieldDecorator('protocol', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.info.netdata.protocol.place' }),
              },
            ],
            initialValue: 1,
          })(
            <Select style={{ width: 485 }}>
              <Option value={1}>
                <FormattedMessage id="app.dm.product.info.netdata.mqtt" />
              </Option>
              <Option value={2}>
                <FormattedMessage id="app.dm.product.info.netdata.tcpip" />
              </Option>
              <Option value={3}>
                <FormattedMessage id="app.dm.product.info.netdata.modbustcp" />
              </Option>
            </Select>,
          )}
        </FormItem>
        <FormItem
          label={formatMessage({ id: 'app.dm.product.info.netdata.decoder' })}
          colon={false}
        >
          {form.getFieldDecorator('decoder', {
            rules: [
              {
                required: true,
                message: formatMessage({ id: 'app.dm.product.info.netdata.decoder.place' }),
              },
            ],
          })(
            <Select
              style={{ width: 485 }}
              placeholder={formatMessage({ id: 'app.dm.product.info.netdata.decoder.place' })}
            >
              {options}
            </Select>,
          )}
        </FormItem>
      </div>
      <Divider orientation="left" style={{ color: '#999', margin: 0, marginTop: 24 }} dashed>
        <FormattedMessage id="app.dm.product.info.more" />
      </Divider>
      <div style={{ width: 530, paddingLeft: 44 }}>
        <FormItem label={formatMessage({ id: 'app.dm.product.info.more.desc' })} colon={false}>
          {form.getFieldDecorator('desc', {
            rules: [],
          })(<TextArea rows={4} />)}
        </FormItem>
      </div>
    </Modal>
  );
});

@connect(({ product, loading }) => ({
  product,
  loading: loading.models.product,
}))
@Form.create()
class Product extends PureComponent {
  state = {
    modalVisible: false,
    isShowJoinGateway: 'block',
  };

  columns = [
    {
      key: 'name',
      title: formatMessage({ id: 'app.dm.product.table.name' }),
      dataIndex: 'name',
    },
    {
      key: 'key',
      title: formatMessage({ id: 'app.dm.product.table.productKey' }),
      dataIndex: 'key',
    },
    {
      key: 'type',
      title: formatMessage({ id: 'app.dm.product.table.nodeType' }),
      render: (text, record) => {
        if (record.type === 1) {
          return <FormattedMessage id="app.dm.product.info.type.device" />;
        }
        if (record.type === 2) {
          return <FormattedMessage id="app.dm.product.info.type.gateway" />;
        }
        return null;
      },
    },
    {
      key: 'protocol',
      title: formatMessage({ id: 'app.dm.product.table.protocol' }),
      render: (text, record) => {
        if (record.protocol === 1) {
          return <FormattedMessage id="app.dm.product.info.netdata.mqtt" />;
        }
        if (record.protocol === 2) {
          return <FormattedMessage id="app.dm.product.info.netdata.tcpip" />;
        }
        if (record.protocol === 3) {
          return <FormattedMessage id="app.dm.product.info.netdata.modbustcp" />;
        }
        return null;
      },
    },
    {
      key: 'gross',
      title: formatMessage({ id: 'app.dm.product.table.deviceNum' }),
      dataIndex: 'gross',
    },
    {
      key: 'createTime',
      title: formatMessage({ id: 'app.dm.product.table.createTime' }),
      dataIndex: 'createTime',
    },
    {
      key: 'action',
      title: formatMessage({ id: 'app.dm.product.table.action' }),
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleView(record)}>
            <FormattedMessage id="app.dm.product.table.action.view" />
          </a>
          <Divider type="vertical" />
          <Link to={`/dm/devices?pid=${record.id}`}>
            {formatMessage({ id: 'app.dm.product.table.action.view.manage' })}
          </Link>
          <Divider type="vertical" />
          <Popconfirm
            title={
              <div style={{ width: 280 }}>
                <div style={{ fontWeight: 'bold', color: '000', marginBottom: 10 }}>
                  <span>
                    {formatMessage({ id: 'app.dm.product.del.confirm' }, { name: record.name })}
                  </span>
                </div>
                <div>
                  <span>{formatMessage({ id: 'app.dm.product.del.prompt' })}</span>
                </div>
              </div>
            }
            onConfirm={() => this.handleDelete(record.id)}
          >
            <a>
              <FormattedMessage id="app.dm.product.table.action.del" />
            </a>
          </Popconfirm>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/fetch',
    });
    dispatch({
      type: 'product/fetchClass',
    });
    dispatch({
      type: 'product/fetchDecoder',
    });
    // dispatch({
    //   type: 'product/fetchModel',
    // });
  }

  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
    });
  };

  handleDelete = id => {
    const { dispatch } = this.props;
    dispatch({
      type: 'product/del',
      payload: id,
    });
  };

  handleView = record => {
    router.push({
      pathname: `/dm/product/detail/${record.id}`,
      state: {
        protocol: record.protocol,
        protocolId: record.protocolId,
      },
    });
  };

  handleAdd = (fields, form) => {
    const { dispatch } = this.props;
    const { handleModalVisible } = this;
    dispatch({
      type: 'product/add',
      payload: {
        name: fields.name,
        classId: fields.class,
        modelId: fields.model,
        type: fields.type,
        isJoinGateway: fields.isJoinGateway,
        net: fields.net,
        protocol: fields.protocol,
        decoderId: fields.decoder,
        desc: fields.desc,
      },
      form,
      handleModalVisible,
    });
  };

  typeChange = e => {
    if (e.target.value === 1) {
      this.setState({
        isShowJoinGateway: 'block',
      });
    } else {
      this.setState({
        isShowJoinGateway: 'none',
      });
    }
  };

  render() {
    const {
      product: { list, pagination, models, current, classes, decoder },
      loading,
      dispatch,
    } = this.props;

    const {
      form: { getFieldDecorator, getFieldsValue },
    } = this.props;

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...pagination,
      onShowSizeChange(curr, size) {
        dispatch({
          type: 'product/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: size } },
        });
      },
      onChange(curr) {
        dispatch({
          type: 'product/fetch',
          payload: { ...getFieldsValue(), ...{ pageNum: curr, pageSize: pagination.currentSize } },
        });
      },
    };

    const search = value => {
      dispatch({
        type: 'product/fetch',
        payload: { name: value },
      });
    };

    const refresh = () => {
      dispatch({
        type: 'product/fetch',
        payload: { ...getFieldsValue() },
      });
    };

    let options = [];

    if (decoder) {
      options = decoder.map(d => <Option key={d.id}>{d.name}</Option>);
    }

    const parentMethods = {
      options,
      classes,
      models,
      current,
      dispatch,
      handleModalVisible: this.handleModalVisible,
      handleAdd: this.handleAdd,
      typeChange: this.typeChange,
      isShowJoinGateway: this.state.isShowJoinGateway,
    };

    const { modalVisible } = this.state;

    return (
      <PageHeaderWrapper title={formatMessage({ id: 'app.dm.product.title' })}>
        <div className={styles.standardList}>
          <Form layout="inline">
            <Card bordered={false}>
              <div className={styles.extraContent}>
                <Row>
                  <Col span={12}>
                    {/* <span style={{fontSize:'16px',color:'rgba(0, 0, 0, 0.85)',fontWeight:500}}><FormattedMessage id="app.dm.product.title" /></span> */}
                    <FormItem>
                      {getFieldDecorator('name')(
                        <Search
                          className={styles.extraContentSearch}
                          placeholder={formatMessage({ id: 'app.dm.product.search' })}
                          onSearch={search}
                        />,
                      )}
                    </FormItem>
                  </Col>
                  <Col span={12} style={{ textAlign: 'right' }}>
                    <FormItem>
                      <Button onClick={refresh}>
                        <FormattedMessage id="app.dm.product.refresh" />
                      </Button>
                    </FormItem>
                    <FormItem style={{ marginRight: 0 }}>
                      <Button type="primary" onClick={() => this.handleModalVisible(true)}>
                        <FormattedMessage id="app.dm.product.add" />
                      </Button>
                    </FormItem>
                  </Col>
                </Row>
                {/* <Row>
                  <FormItem>
                    {getFieldDecorator('name')(
                      <Search  className={styles.extraContentSearch} placeholder={formatMessage({id:'app.dm.product.search'})} onSearch={search} />
                    )}
                  </FormItem>
                </Row> */}
              </div>
              <Table
                columns={this.columns}
                dataSource={list}
                pagination={paginationProps}
                loading={loading}
                rowKey="id"
                style={{ marginTop: 15 }}
              />
            </Card>
          </Form>
        </div>
        <ProductForm {...parentMethods} modalVisible={modalVisible} />
      </PageHeaderWrapper>
    );
  }
}

export default Product;
